//分页参数设置 这些全局变量关系到分页的功能
var startAllAppoint = 1;
var limitAllAppoint = 10;
var currentPageAllAppoint = 1;
var totalPageAllAppoint = 0;
var dataLength = 0;
layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;
	//加载页面数据
	getPageList();
	toPage();
	//查询
	$(".search_btn").click(function(){
		startAllAppoint =1;
		currentPageAllAppoint =1;
		getPageList();
		
		toPage();
	})

	//添加会员
	$(".add_btn").click(function(){
		var index = layui.layer.open({
			title : "添加入库单",
			type : 2,
			content : "storagebillAdd.html",
			success : function(layero, index){
				
				layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
					tips: 3
				}
				);
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})
	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.vo_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.vo_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
					var delIdArray = [];
					for(var j=0;j<$checked.length;j++){
            			var delId = $checked.eq(j).attr("data-id");
            			delIdArray.push(delId);
	            	}
				$.ajax({
			        url: API_URL_HEAD+"putInBills/batchDelete/",
			        type: 'post',
			        async: false,
			        data:JSON.stringify(delIdArray),
			        contentType: 'application/json; charset=utf-8',
			        dataType: 'json',
			        success: function (data) {
			        	var vo = data.data;
			        	$('.vo_list thead input[type="checkbox"]').prop("checked",false);
		            	startAllAppoint =1;
						currentPageAllAppoint =1;
						getPageList();
						toPage();
		                layer.close(index);
						layer.msg("删除成功");
			        }
			  });	          
	        })
		}else{
			layer.msg("请选择需要删除的记录");
		}
	})
    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//操作
	$("body").on("click",".users_edit",function(){  //编辑
		var _this = $(this);
		var index = layui.layer.open({
			title : "编辑送水人员",
			type : 2,
			content : "watermanEdit.html",
			success : function(layero, index){			
				$.ajax({
			        url: API_URL_HEAD+"deliveryMan/detail/"+_this.attr("data-id"),
			        type: 'get',
			        async: false,
			        contentType: 'application/json; charset=utf-8',
			        dataType: 'json',
			        success: function (data) {
			        	var vo = data.data;
			        	$("#id", layero.find("iframe")[0].contentWindow.document).val(_this.attr("data-id"));
			        	$(".deliveryName", layero.find("iframe")[0].contentWindow.document).val(data.data.deliveryName);
			        	$(".deliveryAdder", layero.find("iframe")[0].contentWindow.document).val(data.data.deliveryAdder);
			        	$(".deliveryTel", layero.find("iframe")[0].contentWindow.document).val(data.data.deliveryTel);
			 			
						layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
							tips: 3
						});
			        }
			   });
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})

	$("body").on("click",".users_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
				$.ajax({
			        url: API_URL_HEAD+"putInBills/deleteById/"+_this.attr("data-id"),
			        type: 'get',
			        async: false,
			        contentType: 'application/json; charset=utf-8',
			        dataType: 'json',
			        success: function (data) {
			        	var vo = data.data;
						layer.close(index);
						startAllAppoint =1;
						currentPageAllAppoint =1;
						getPageList();
						toPage();
			        }
			  });

		});
	})          

function getPageList(){
	var data={
		"searchKey":$(".search_input").val()
	};
	var pageData ={
		"page":startAllAppoint,
		"limit":limitAllAppoint
		};
		$.extend(data, pageData);
	    $.ajax({
        url: API_URL_HEAD+"putInBills/queryPage",
        type: 'post',
        async: false,
        data :JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
        	var list = data.data.list;
        	renderData(list);
        	startAllAppoint = data.data.pageNum;//当前页数(后台返回)
        	totalPageAllAppoint = data.data.pages;//总页数(后台返回)
        }
    });
}

function renderData(data){
	var dataHtml = '';
	if(data.length != 0){
		for(var i=0;i<data.length;i++){
			dataHtml += '<tr>'
	    	+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose" data-id="'+data[i].id+'"></td>'
	    	+  '<td>'+data[i].billSn+'</td>'
	    	+  '<td>'+data[i].waterName+'</td>'
	    	+  '<td>'+data[i].waterNum+'</td>'
	    	+  '<td>'+data[i].remark+'</td>'
	    	+  '<td>'
			+    '<a class="layui-btn layui-btn-mini users_edit" data-id="'+data[i].id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
			+    '<a class="layui-btn layui-btn-danger layui-btn-mini users_del" data-id="'+data[i].id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
	        +  '</td>'
	    	+'</tr>';
		}
	}else{
		dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
	}
	$(".vo_content").html(dataHtml);
}
function toPage(){
    var nums = 10;
    //调用分页
      laypage({
        cont: 'page'
        ,pages: totalPageAllAppoint //得到总页数
        ,curr: currentPageAllAppoint
        ,skip: true
        ,jump: function(obj, first){
            currentPageAllAppoint = obj.curr;
            startAllAppoint = obj.curr;
          if(!first){ //一定要加此判断，否则初始时会无限刷新
          	getPageList();//一定要把翻页的ajax请求放到这里，不然会请求两次。
               }
          	form.render();
            }
         });
};
   
})

